/*
 * @Date: 2020-10-20 02:07:21
 * @LastEditors: Tonser
 * @LastEditTime: 2020-10-25 16:23:50
 * @FilePath: /swarm_ws/src/px4_gcs/src/Utils/CSVManager.h
 * @Description: CSV 工具类
 */
#pragma once


#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

template<class T>
class CSVManager
{
private:
    std::string filePath = "";
public:
    void setFilePath(std::string filepath);
    bool readCSV(vector<vector<T>> &traj);
    CSVManager() = default;
    CSVManager(std::string filepath);
    ~CSVManager();
};
template<class T>
CSVManager<T>::CSVManager(std::string filepath){
    filePath = filepath;
}

template<class T> void
CSVManager<T>::setFilePath(std::string filepath){
    filePath = filepath;
}

template<class T>
CSVManager<T>::~CSVManager()
{
}

template<class T>
bool CSVManager<T>::readCSV(vector<vector<T>> &traj) {
    ifstream traj_file(filePath);
    if (traj_file.fail()) {
        std::cout << "[ERROR] invalid file path!!" << filePath <<endl;
        return false;
    }
    if(!traj.empty()){
        traj.clear();
    }
    string line;
    while (getline(traj_file, line)) {
        istringstream in_line(line);
        vector<T> dataInLine;
        string word;
        T value;
        while (getline(in_line, word, ',')) {
            if(typeid(value) == typeid(float)){
                dataInLine.push_back(strtof(word.c_str(), nullptr));
            }
            if(typeid(value) == typeid(double)){
                dataInLine.push_back(strtod(word.c_str(), nullptr));
            }
        }
        if (!dataInLine.empty()) traj.push_back(dataInLine);
    }
    std::cout << "read csv finished !!!"<<endl;
    return !traj.empty();
}
